package com.yql.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper;
import com.baomidou.mybatisplus.extension.kotlin.KtUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yql.common.core.domain.entity.Commodity;
import com.yql.common.core.domain.entity.Order;
import com.yql.common.core.domain.response.TopThreeCommodityRsp;
import com.yql.common.core.redis.RedisCache;
import com.yql.common.enums.OrderStatusEnum;
import com.yql.common.enums.RefundStatusEnum;
import com.yql.common.exception.BusinessException;
import com.yql.common.utils.ShiroUtils;
import com.yql.common.utils.uuid.IdUtils;
import com.yql.system.mapper.OrderMapper;
import com.yql.common.core.domain.request.OrderListReq;
import com.yql.common.core.domain.request.PlaceOrderReq;
import com.yql.system.service.ICommodityService;
import com.yql.system.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 商品服务
 *
 * @author longxiaoxiao
 * @version 1.0
 * @date 2021/12/23 11:59
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Resource
    private RedisCache redisCache;

    @Resource
    private ICommodityService commodityService;

    /**
     * 下单
     *
     * @param req
     * @Date 2021/12/24 9:39
     * @Author longxiao
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String placeOrder(PlaceOrderReq req) {
        // 从redis里扣库存，成功则进行下单，失败则返回。
        // TODO
       /*  用户下单间隔5秒
        boolean setKeyResult = redisCache.setNxByCustomTime(ShiroUtils.getUserId() + String.valueOf(req.getCommodityId()), 0, 5L, TimeUnit.SECONDS);
        if (!setKeyResult){
            throw new BusinessException("请稍后下单");
        }*/
        Commodity commodity = commodityService.getById(req.getCommodityId());
        String orderNo = IdUtils.simpleUUID();
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setOrderAmount(new BigDecimal(req.getCommodityCount()).multiply(commodity.getCommodityAmount()));
        order.setCommodityCount(req.getCommodityCount());
        order.setCommodityId(commodity.getId());
        order.setUserId(ShiroUtils.getUserId());
        order.setOrderStatus(OrderStatusEnum.P.getCode());
        order.setRefundStatus(RefundStatusEnum.N.getCode());
        log.info("为用户{} 选择的{} 进行下单 {}", ShiroUtils.getSysUser(), commodity, order);
        baseMapper.insert(order);
        log.info("扣除库存=={======>");
        LambdaUpdateWrapper<Commodity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.setSql("commodity_num = commodity_num - " + req.getCommodityCount())
                .eq(Commodity::getId, req.getCommodityId());
        commodityService.update(updateWrapper);
        return orderNo;
    }

    /**
     * 条件分页查询订单列表
     *
     * @param req
     * @Date 2021/12/24 11:55
     * @Author longxiao
     */
    @Override
    public List<Order> selectList(OrderListReq req) {
        return baseMapper.list(req);
    }

    /**
     * 订单销量排名前三的商品及订单数量
     *
     * @Date 2021/12/24 14:42
     * @Author longxiao
     */
    @Override
    public List<TopThreeCommodityRsp> topThreeCommodity(Long topNum) {
        return baseMapper.topThreeCommodity(topNum);
    }

}
